package cn.b.sky.mes.cm.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.b.sky.mes.cm.model.MateriaProcessAssign;
import cn.b.sky.mes.cm.model.Material;
import cn.b.sky.mes.cm.model.MaterialType;
import cn.b.sky.mes.cm.model.WorkCenter;
import cn.b.sky.mes.cm.model.condition.MaterialCondition;
import cn.b.sky.mes.cm.model.condition.ProcessCondition;
import cn.b.sky.mes.cm.service.MaterialService;
import cn.b.sky.mes.cm.service.MaterialTypeService;
import cn.b.sky.mes.cm.service.ProcessService;
import cn.b.sky.mes.cm.service.WorkCenterService;
import cn.b.sky.mes.cm.service.WorkCenterTypeService;
import cn.b.sky.common.constants.SystemConstant;
import cn.b.sky.common.model.BatchJobReport;
import cn.b.sky.common.model.DWZResult;
import cn.b.sky.user.SecurityContextUtil;
import cn.b.sky.user.controller.SecurityController;

@Controller
@RequestMapping(value = "/material/*")
public class MaterialController extends SecurityController {
  @Resource
  MaterialService materialService;

  @Resource
  MaterialTypeService materialTypeService;

  @Resource
  private ProcessService processService;

  @Resource
  private WorkCenterTypeService workCenterTypeService;

  @Resource
  WorkCenterService workCenterService;

  @RequestMapping("materialList")
  public String numberRuleList(Model model, @ModelAttribute("condition") MaterialCondition material, String navTabId) {
    material.setSiteCode(SecurityContextUtil.getSiteCode());
    List<MaterialType> types = materialTypeService.selectAllUnLockeMaterialTypes(SecurityContextUtil.getSiteCode());
    model.addAttribute("materialTypes", types);
    if (StringUtils.isEmpty(material.getOrderField())) {
      material.setOrderField("createDateTime");
    }
    material.setCurrentTime(new Date());
    List<Material> materialList = materialService.selectMaterialList(material);
    int count = materialService.selectMaterialListCount(material);
    material.setData(materialList);
    material.setTotalCount(count);
    model.addAttribute("page", material);
    model.addAttribute(NAVTABID, navTabId);
    return "cm/material/material_list";
  }

  @RequestMapping("addMaterial")
  public String addMaterial(Model model, String navTabId) {
    List<MaterialType> types = materialTypeService.selectAllUnLockeMaterialTypes(SecurityContextUtil.getSiteCode());
    model.addAttribute("materialTypes", types);
    model.addAttribute(NAVTABID, navTabId);
    List<WorkCenter> workCenters = workCenterService.getAllWorkCenterListBySiteCode(getSiteCode(), 0);
    model.addAttribute("workCenters", workCenters);
    return "cm/material/material_add";
  }

  @RequestMapping("editMaterial")
  public String editMaterial(Model model, String navTabId, String id) {
    List<MaterialType> types = materialTypeService.selectAllUnLockeMaterialTypes(SecurityContextUtil.getSiteCode());
    model.addAttribute("materialTypes", types);
    model.addAttribute(NAVTABID, navTabId);
    Material material = materialService.selectMaterial(getSiteCode(), id);
    model.addAttribute("material", material);
    List<MateriaProcessAssign> processes = materialService.selectProcessByMaterial(getSiteCode(), id);
    model.addAttribute("processes", processes);
    List<WorkCenter> workCenters = workCenterService.getAllWorkCenterListBySiteCode(getSiteCode(), 0);
    model.addAttribute("workCenters", workCenters);
    return "cm/material/material_add";
  }

  @RequestMapping("selectProcess")
  public String selectProcess(Model model, String navTabId, @ModelAttribute("condition") ProcessCondition condition) {
    if (condition == null) {
      condition = new ProcessCondition();
    }
    condition.setSiteCode(getSiteCode());
    model.addAttribute("workCenterType", workCenterTypeService.selectAllWorkCenterType(this.getSiteCode()));
    model.addAttribute("page", processService.getNoVersionProcessPageByCondition(condition));
    model.addAttribute(NAVTABID, navTabId);
    return "cm/material/process_select";
  }

  @RequestMapping("validateMaterialCode")
  @ResponseBody
  public boolean validateMaterialCode(String materialCode, Model model) {
    if (!StringUtils.isBlank(materialCode)) {
      return null == materialService.selectMaterial(getSiteCode(), materialCode);
    }
    return true;
  }

  @RequestMapping("saveMaterial")
  @ResponseBody
  public DWZResult saveMaterial(Model model, String navTabId, String process, String id, Material material,
      HttpServletRequest request) {
    if (material == null) {
      return ajaxError(getImeViewMessageI18n(null, SystemConstant.PARAMETERNULL));
    }
    material.setSiteCode(getSiteCode());

    // 处理工艺路线
    if (!StringUtils.isEmpty(process)) {
      List<MateriaProcessAssign> processList = new ArrayList<MateriaProcessAssign>();
      String[] processes = process.split(",");
      for (String s : processes) {
        MateriaProcessAssign p = new MateriaProcessAssign();
        p.setSiteCode(getSiteCode());
        p.setMaterialCode(material.getMaterialCode());
        p.setProcessCode(s);
        processList.add(p);
      }
      material.setProcessList(processList);
    }
    setCreateInfo(material);
    if (StringUtils.isEmpty(id)) {
      materialService.insertMaterial(material);

      return dialogAjaxDone(getImeViewMessageI18n(null, "successfulOperation.M"), null, null, null, null);
    } else {
      materialService.updateMaterial(material);
      return dialogAjaxDone(getImeViewMessageI18n(null, "successfulOperation.M"), null, null, null, null);

    }

  }

  @RequestMapping("viewMaterial")
  public String viewMaterial(Model model, String navTabId, String id) {
    List<MaterialType> types = materialTypeService.selectAllUnLockeMaterialTypes(SecurityContextUtil.getSiteCode());
    model.addAttribute("materialTypes", types);
    model.addAttribute(NAVTABID, navTabId);
    Material material = materialService.selectMaterial(getSiteCode(), id);
    model.addAttribute("material", material);
    List<MateriaProcessAssign> processes = materialService.selectProcessByMaterial(getSiteCode(), id);
    model.addAttribute("processes", processes);
    List<WorkCenter> workCenters = workCenterService.getAllWorkCenterListBySiteCode(getSiteCode(), 0);
    model.addAttribute("workCenters", workCenters);
    return "cm/material/material_view";
  }

  @RequestMapping("deleteMaterial")
  @ResponseBody
  public DWZResult deleteMaterial(Model model, String navTabId, HttpServletRequest request) {
    String ids = request.getParameter("ids");
    String[] ress = ids.split(",");
    List<BatchJobReport> reports = new ArrayList<BatchJobReport>(ress.length);
    boolean hasFail = false;
    for (String res : ress) {
      BatchJobReport report = materialService.deleteMaterial(getSiteCode(), res);
      reports.add(report);
      if (!report.isSuccess()) {
        hasFail = true;
      }
    }
    if (!hasFail) {
      // 直接返回成功消息
      return navTabAjaxDone(navTabId, null, null, null, getImeViewMessageI18n(null, "successfulOperation.M"), null);
    } else {
      return batchjobAjaxDone(request, reports);
    }

  }

  @RequestMapping("componentLookUp")
  public String componentLookUp(Model model, String lookupType, @ModelAttribute("condition") MaterialCondition material) {
    material.setSiteCode(this.getSiteCode());
    List<MaterialType> types = materialTypeService.selectAllUnLockeMaterialTypes(SecurityContextUtil.getSiteCode());
    model.addAttribute("materialTypes", types);
    material.setCurrentTime(new Date());
    List<Material> materialList = materialService.selectMaterialList(material);
    int count = materialService.selectMaterialListCount(material);
    material.setData(materialList);
    material.setTotalCount(count);
    model.addAttribute("page", material);
    if (!StringUtils.isBlank(lookupType) && "radio".equals(lookupType)) {
      return "cm/material/material_lookup_radio";
    }
    return "cm/material/material_lookup_multi";
  }

  @RequestMapping("componentSuggest")
  @ResponseBody
  public Object componentSuggest(@ModelAttribute("condition") MaterialCondition material) {
    material.setSiteCode(this.getSiteCode());
    material.setCurrentTime(new Date());
    return materialService.selectMaterialSuggests(material);
  }

  @RequestMapping("componentLookUpForBOM")
  public String componentLookUpForBOM(Model model, String lookupType,
      @ModelAttribute("condition") MaterialCondition material) {
    material.setSiteCode(this.getSiteCode());
    List<MaterialType> types = materialTypeService.selectAllUnLockeMaterialTypes(SecurityContextUtil.getSiteCode());
    model.addAttribute("materialTypes", types);
    material.setCurrentTime(new Date());
    List<Material> materialList = materialService.selectMaterialList(material);
    int count = materialService.selectMaterialListCount(material);
    material.setData(materialList);
    material.setTotalCount(count);
    model.addAttribute("page", material);
    return "cm/material/material_lookup_multi";
  }

  @RequestMapping("validateMaterial")
  @ResponseBody
  public boolean validateMaterial(Model model, String navTabId, String materialCode) {
    Material material = materialService.selectMaterial(getSiteCode(), materialCode);
    return material != null;
  }
}
